import json
import os

from dotenv import load_dotenv
from flask import Flask, request, jsonify, send_file
from flask_cors import CORS
from cozepy import Coze, TokenAuth, COZE_CN_BASE_URL

# 加载环境变量
load_dotenv()

# 创建flask应用实例
app = Flask(__name__)
# 允许跨域请求
CORS(app)

# 调用工作流生成视频
def create_video(animal_desc):
    try:
        # 获取环境变量
        api_token = os.getenv('COZE_API_TOKEN')
        workflow_id = os.getenv('WORKFLOW_ID')

        # 创建coze客户端
        coze = Coze(
            auth=TokenAuth(token=api_token),
            base_url=COZE_CN_BASE_URL
        )

        # 执行工作流
        workflow = coze.workflows.runs.create(
            workflow_id=workflow_id,
            parameters={
                "input": animal_desc
            }
        )

        # 接收返回的内容
        video_url = json.loads(workflow.data)['output']

        return video_url
    except Exception as e:
        return str(e)

# 声明接口路由
@app.route('/generate_video', methods=['POST'])
def generate_video():
    data = request.get_json()
    animal_desc = data.get('input', '').strip()

    video_url = create_video(animal_desc)

    return jsonify(
        {
            'success': True,
            'animal_desc': animal_desc,
            'video_url': video_url
        }
    )

@app.route('/')
def index():
    return send_file('index.html')



if __name__ == '__main__':
    app.run(debug=True, port=5000)

